package com.eastfair.auth.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.eastfair.annotation.annotation.cache.Cache;
import com.eastfair.annotation.annotation.cache.Magic;
import com.eastfair.auth.dao.OrganizationMapper;
import com.eastfair.auth.dto.HuaWeiOrganizationDTO;
import com.eastfair.auth.dto.OrganizationDTO;
import com.eastfair.auth.dto.ResourceOrganizationSaveDTO;
import com.eastfair.auth.dto.RoleDTO;
import com.eastfair.auth.entity.*;
import com.eastfair.auth.enumeration.*;
import com.eastfair.auth.service.*;
import com.eastfair.auth.util.DataIsoLotionUtil;
import com.eastfair.auth.vo.*;
import com.eastfair.boot.service.SuperCacheServiceImpl;
import com.eastfair.cache.auth.InterfaceCacheKeyBuilder;
import com.eastfair.cache.auth.OrganizationCacheKeyBuilder;
import com.eastfair.cache.auth.PermissionCacheKeyBuilder;
import com.eastfair.cache.repository.CacheOps;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.core.model.CacheKey;
import com.eastfair.core.model.CacheKeyBuilder;

import com.eastfair.log.point.PointUtil;
import com.eastfair.model.DataIsolationVo;
import com.eastfair.projectcore.api.ProjectCoreServiceFeign;

import com.eastfair.projectcore.dto.MenuDTO;
import com.eastfair.projectcore.enumeration.MenuAffiliationEnum;
import com.eastfair.projectcore.enumeration.MenuSceneEnum;
import com.eastfair.projectcore.vo.MenuVO;
import com.eastfair.uid.baidu.rule.SnowFlakeRole;
import com.eastfair.util.CodeUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static com.eastfair.core.base.R.SUCCESS_CODE;
import static com.eastfair.core.exception.code.ExceptionCode.MEUN_MORE;
import static com.eastfair.core.exception.code.ExceptionCode.NODE_NO;

/**
 * <p>
 * 业务实现类
 *
 * </p>
 *
 * @author ligang
 * @date 2021-07-16
 */
@Slf4j
@Service
//@DSTransactional
//@DS("#thread.tenant")

public class OrganizationServiceImpl extends SuperCacheServiceImpl<OrganizationMapper, Organization> implements OrganizationService {

    @Autowired
    ProjectCoreServiceFeign projectCoreServiceFeign;

    @Autowired
    UserOrganizationService userOrganizationService;

    @Autowired
    ResourceOrganizationService resourceOrganizationService;

    @Autowired
    RoleService roleService;

    @Autowired
    UserRoleService userRoleService;

    @Autowired
    OrganizationRoleService organizationRoleService;

    @Autowired
    MenuRoleService menuRoleService;

    @Autowired
    protected CacheOps cacheOps;

    @Autowired
    private PointUtil pointUtil;

    @Autowired
    SnowFlakeRole snowFlakeRole;

    @Override
    public CacheKeyBuilder getCacheKeyBuilder() {
        return new OrganizationCacheKeyBuilder();
    }

    /**
     * 处理新增相关处理
     *
     * @param model 实体
     * @return 是否成功
     */
    @Override
    protected R<Boolean> handlerSave(Organization model) {
        model.setId(snowFlakeRole.findUidSimple());
        model.setProjectId(ContextUtil.getProjectId());
        model.setSubsystemId(ContextUtil.getSubSystemId());
        model.setTeamId(ContextUtil.getTeamId());
        if (model.getParentId() == null) {
            //组织顶级为1000
            model.setParentId(BusinessConstant.parentId);
        }

        //code 码
        if (StringUtils.isBlank(model.getCode())) {
            model.setCode(queryCode(model));
        }
        if (model.getSequence() == null) {
            //排序
            model.setSequence(1);
            if (model.getParentId() != null) {
                model.setSequence(querySort(model.getParentId()));
            }
        }
        return R.successDef();
    }


    @Override
    public R del(Long id) {
        Organization organization = getByIdCache(id);
        if (organization != null) {
            removeResourceUserOfOrg(Arrays.asList(id));
            //同时删除旗下子节点
            delChild(organization);
            organization.setIsDeleted(BusinessConstant.DELETE_YES);
            updateById(organization);
        }
        return R.successDef();
    }

    @Override
    public R delChild(Organization organization) {
        if (organization != null) {
            String code = organization.getCode();
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setCode(code + ",");
            List<Organization> organizationList = queryAllOfCode(organizationDTO);
            if (organizationList != null && !organizationList.isEmpty()) {
                for (Organization organization1 : organizationList) {
                    organization1.setIsDeleted(BusinessConstant.DELETE_YES);
                    updateById(organization1);
                }
                //剔除组织关联的资源和用户
                List<Long> orgIds = organizationList.stream().map(Organization::getId).collect(Collectors.toList());
                removeResourceUserOfOrg(orgIds);
            }
        }
        return R.successDef();
    }

    @Override
    public int querySort(Long parentId) {
        if (parentId == 0) {
            return 1;
        }
        List<Organization> organizationList = queryEntityOfParentId(parentId);
        if (organizationList != null && !organizationList.isEmpty()) {
            int max = organizationList.stream().mapToInt(Organization::getSequence).max().getAsInt();
            return max + 1;
        }
        return 1;
    }

    @Override
    public String queryCode(Organization model) {
        String code = nonredundantCode();
        if (model.getParentId() != 0) {
            Organization organization = getByIdCache(model.getParentId());
            if (organization != null) {
                code = organization.getCode() + "," + code;
            }
        }
        return code;
    }

    /**
     * 获取不重复的code
     *
     * @return
     */
    public String nonredundantCode() {
        String code = CodeUtils.randomCode(6);
        //是否重复
        int num = queryCodeSize(code);
        if (num > 0) {
            nonredundantCode();
        }
        return code;
    }

    @Override
    public void sortTop(Long id) {
        Organization organization = getByIdCache(id);
        if (organization.getParentId() == 0) {
            return;
        }
        organization.setSequence(1);
        updateById(organization);
        List<Organization> organizationList = queryEntityOfParentId(organization.getParentId());
        int num = 2;
        if (organizationList != null && !organizationList.isEmpty()) {
            for (Organization organization1 : organizationList) {
                if (!organization1.getId().equals(id)) {
                    organization1.setSequence(num++);
                    updateById(organization1);
                }
            }
        }
    }

    @Override
    public void initSort(Long parentId) {
        List<Organization> organizationList = queryEntityOfParentId(parentId);
        if (organizationList != null && !organizationList.isEmpty()) {
            int num = 1;
            for (Organization organization : organizationList) {
                organization.setSequence(num++);
                updateById(organization);
            }
        }
    }

    @Override
    @Cache(key = "",
            magic = @Magic(
                    key = "{{'code', #args[0]?.code,'like'},{'orgType', #args[0]?.orgTypeList},{'orgType', #args[0]?.orgType}," +
                            "{'name', #args[0]?.name},{'code', #args[0]?.codes}}"))
    public List<Organization> queryAllOfCode(OrganizationDTO organizationDTO) {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(organizationDTO.getCode())) {
            queryWrapper.lambda().likeRight(Organization::getCode, organizationDTO.getCode());
        }

        if (organizationDTO.getOrgTypeList() != null && !organizationDTO.getOrgTypeList().isEmpty()) {
            queryWrapper.lambda().in(Organization::getOrgType, organizationDTO.getOrgTypeList());
        }
        if (organizationDTO.getOrgType() != null) {
            queryWrapper.lambda().eq(Organization::getOrgType, organizationDTO.getOrgType());
        }

        if (StringUtils.isNotBlank(organizationDTO.getName())) {
            queryWrapper.lambda().eq(Organization::getName, organizationDTO.getName());
        }

        if (organizationDTO.getCodes() != null && !organizationDTO.getCodes().isEmpty()) {
            queryWrapper.lambda().and(wq -> {
                for (String code : organizationDTO.getCodes()) {
                    wq.likeRight(Organization::getCode, code);
                    wq.or();
                }
            });
        }
        queryWrapper.lambda().eq(Organization::getIsDeleted, BusinessConstant.DELETE_NO);
        //排序查询
        queryWrapper.orderByAsc("sequence");
        List<Organization> organizationList = list(queryWrapper);
        return organizationList;
    }

    @Override
    public List<Organization> queryAllOfCode(List<Long> orgIds) {
        if (orgIds == null || orgIds.isEmpty()) {
            return null;
        }
        List<Organization> result = new ArrayList<>();
        for (Long orgId : orgIds) {
            Organization organization = getByIdCache(orgId);
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setCode(organization.getCode());
            List<Organization> organizationList = queryAllOfCode(organizationDTO);
            if (organizationList != null && !organizationList.isEmpty()) {
                result.addAll(organizationList);
            }
        }
        return result;
    }

    @Override
    public int queryCodeSize(String code) {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(code)) {
            queryWrapper.lambda().eq(Organization::getCode, code);
        }
        queryWrapper.lambda().eq(Organization::getIsDeleted, BusinessConstant.DELETE_NO);
        return count(queryWrapper);
    }

    @Override
    public OrganizationVo loadTree(String parentCode, List<OrganizationVo> organizationVoList) {
        List<OrganizationVo> tree = new ArrayList<>();
        //加载全部角色和菜单
        List<Long> orgIds = organizationVoList.stream().map(OrganizationVo::getId).collect(Collectors.toList());
        //将组织的角色全部查询出来
        Map<Long, List<RoleVo>> roleOfMap = loadRoleOfMap(orgIds);
        //将角色的菜单查询出来
        Map<Long, List<MenuVO>> menuOrRoleMap = null;
        if (roleOfMap != null) {
            List<RoleVo> roleVoResult = new ArrayList<>();
            for (List<RoleVo> roleVoList : roleOfMap.values()) {
                if (roleVoList != null && !roleVoList.isEmpty()) {
                    roleVoResult.addAll(roleVoList);
                }
            }
            menuOrRoleMap = loadMenuOfMap(roleVoResult);
        }

        //加载组织的角色
        for (OrganizationVo organizationVo : organizationVoList) {
            //加载角色和菜单
            List<RoleVo> roleVoList = roleOfMap.get(organizationVo.getId());
            organizationVo.setRoleVoList(roleVoList);
            List<MenuVO> menuVOList = new ArrayList<>();
            if (roleVoList != null && !roleVoList.isEmpty() && menuOrRoleMap != null) {
                for (RoleVo roleVo : roleVoList) {
                    //通过角色查菜单
                    List<MenuVO> menuVOList1 = menuOrRoleMap.get(roleVo.getId());
                    if (menuVOList1 != null && !menuVOList1.isEmpty()) {
                        menuVOList.addAll(menuVOList1);
                    }
                }
            }
            organizationVo.setMenuVOList(menuVOList);
        }

        for (OrganizationVo organizationVo : organizationVoList) {
            //找到根节点
            if (organizationVo.getCode().equals(parentCode)) {
                tree.add(findChildren(organizationVo, organizationVoList, roleOfMap, menuOrRoleMap));
                break;
            }
        }
        return tree.get(0);
    }

    /**
     * 查找子节点
     *
     * @param organizationVo 根节点
     * @param list
     * @return
     */
    private OrganizationVo findChildren(OrganizationVo organizationVo, List<OrganizationVo> list, Map<Long, List<RoleVo>> roleOfOrgMap, Map<Long, List<MenuVO>> menuOfRoleMap) {
        List<OrganizationVo> children = new ArrayList<>();
        for (OrganizationVo node : list) {
            if (node.getParentId().equals(organizationVo.getId())) {
                //递归调用
                OrganizationVo organizationVo1 = findChildren(node, list, roleOfOrgMap, menuOfRoleMap);
//                //加载角色和菜单
//                List<RoleVo> roleVoList = roleOfOrgMap.get(organizationVo1.getId());
//                organizationVo1.setRoleVoList(roleVoList);
//                List<MenuVO> menuVOList = new ArrayList<>();
//                if (roleVoList != null && !roleVoList.isEmpty() && menuOfRoleMap != null) {
//                    for (RoleVo roleVo : roleVoList) {
//                        List<MenuVO> menuVOList1 = menuOfRoleMap.get(roleVo.getId());
//                        if(menuVOList1!=null && !menuVOList1.isEmpty()){
//                            menuVOList.addAll(menuVOList1);
//                        }
//                    }
//                }
//                organizationVo1.setMenuVOList(menuVOList);
//                //之前代码
////                List<RoleVo> roleVoList = loadRole(Arrays.asList(organizationVo1.getId()));
////                organizationVo1.setRoleVoList(roleVoList);
////                organizationVo1.setMenuVOList(loadMenu(roleVoList));
                children.add(organizationVo1);
            }
        }
        organizationVo.setChildVoList(children);
        return organizationVo;
    }


    @Override
    public R<Organization> createOrg(OrganizationDTO organizationDTO) {
        //判断是否超出上级菜单角色
        if (organizationDTO.getRoleIds() != null && !organizationDTO.getRoleIds().isEmpty()) {
            List<RoleVo> roleVoList = new ArrayList<>();
            for (Long roleId : organizationDTO.getRoleIds()) {
                RoleVo roleVo = new RoleVo();
                roleVo.setId(roleId);
                roleVoList.add(roleVo);
            }
            List<MenuRole> menuRoleList = loadMenuRole(roleVoList);
            if (menuRoleList != null && !menuRoleList.isEmpty()) {
                R r = verifyMenuIsOver(organizationDTO.getParentId(), menuRoleList.stream().map(MenuRole::getMenuId).collect(Collectors.toList()));
                if (SUCCESS_CODE != r.getCode()) {
                    return r;
                }
            }
        }
        Organization organization = new Organization();
        organization.setOrgType(organizationDTO.getOrgType());
        organization.setName(organizationDTO.getName());
        if (organizationDTO.getParentId() != null) {
            organization.setParentId(organizationDTO.getParentId());
        }
        organization.setVestType(organizationDTO.getVestType());
        save(organization);
        if (organizationDTO.getResourceId() != null) {
            //添加资源
            ResourceOrganizationSaveDTO resourceOrganizationSaveDTO = new ResourceOrganizationSaveDTO();
            resourceOrganizationSaveDTO.setResourceId(organizationDTO.getResourceId());
            resourceOrganizationSaveDTO.setResourceType(organizationDTO.getResourceType());
            resourceOrganizationSaveDTO.setOrganizationId(organization.getId());
            resourceOrganizationService.createResource(resourceOrganizationSaveDTO);
        }
        if (organizationDTO.getUserIds() != null && !organizationDTO.getUserIds().isEmpty()) {
            //添加用户信息，如果在组织组上添加用户，说明该用户是管理员
            userOrganizationService.addUserOfOrg(organization.getId(), organizationDTO.getUserIds(), organizationDTO.getIsLeader());
        }
        //添加角色
        if (organizationDTO.getRoleIds() != null && !organizationDTO.getRoleIds().isEmpty()) {
            //通过角色
            R r = addOrgRole(organization.getId(), organizationDTO.getRoleIds(), false);
            if (SUCCESS_CODE != r.getCode()) {
                return r;
            }
        }
        return R.success(organization);
    }

    @Override
    public R<Organization> updOrg(OrganizationDTO organizationDTO) {
        List<Organization> organizationList = listOfOrganization(null, Arrays.asList(organizationDTO.getOrgId()));
        if (organizationList != null && !organizationList.isEmpty()) {
            Organization organization = organizationList.get(0);
            //判断是否超出上级菜单角色
            if (organizationDTO.getRoleIds() != null && !organizationDTO.getRoleIds().isEmpty()) {
                List<RoleVo> roleVoList = new ArrayList<>();
                for (Long roleId : organizationDTO.getRoleIds()) {
                    RoleVo roleVo = new RoleVo();
                    roleVo.setId(roleId);
                    roleVoList.add(roleVo);
                }
                List<MenuRole> menuRoleList = loadMenuRole(roleVoList);
                if (menuRoleList != null && !menuRoleList.isEmpty()) {
                    R r = verifyMenuIsOver(organization.getParentId(), menuRoleList.stream().map(MenuRole::getMenuId).collect(Collectors.toList()));
                    if (SUCCESS_CODE != r.getCode()) {
                        return r;
                    }
                }
            }

            organization.setName(organizationDTO.getName());
            updateById(organization);
            if (organizationDTO.getUserIds() != null && !organizationDTO.getUserIds().isEmpty()) {
                //删除用户关联信息
                userOrganizationService.removeUserOfOrg(organization.getId(), organizationDTO.getUserIds());
                //添加用户信息，如果在组织组上添加用户，说明该用户是管理员
                userOrganizationService.addUserOfOrg(organization.getId(), organizationDTO.getUserIds(), organizationDTO.getIsLeader());
            }
            //添加角色
            if (organizationDTO.getRoleIds() != null && !organizationDTO.getRoleIds().isEmpty()) {
                //更新角色
                R r = updOrgRole(organization.getId(), organizationDTO.getRoleIds(), false);
                if (SUCCESS_CODE != r.getCode()) {
                    return r;
                }
            }
            return R.success(organization);
        }
        return R.fail("操作失败");
    }

    @Override
    public List<Organization> queryEntityOfParentId(Long parentId) {
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Organization::getParentId, parentId);
        queryWrapper.lambda().eq(Organization::getIsDeleted, BusinessConstant.DELETE_NO);
        //排序查询
        queryWrapper.orderByAsc("sequence");
        return list(queryWrapper);
    }

    @Override
    public OrganizationVo findAllById(Long id) {
        Organization organization = getByIdCache(id);
        if (organization != null) {
            String code = organization.getCode();
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setCode(code);
            organizationDTO.setOrgTypeList(queryChildType(organization.getOrgType()));
            List<Organization> childOrganizationList = ((OrganizationService) AopContext.currentProxy()).queryAllOfCode(organizationDTO);
            List<OrganizationVo> organizationVoList = doToVos(childOrganizationList);
            if (organizationVoList == null || organizationVoList.isEmpty()) {
                organizationVoList = new ArrayList<>();
            }
            organizationVoList.add(doToVo(organization));
            //将用户和资源加载进去
            loadUserAndResource(organizationVoList);
            OrganizationVo organizationVo = loadTree(code, organizationVoList);
            //将角色加载进去
            List<Long> orgIds = organizationVoList.stream().map(OrganizationVo::getId).collect(Collectors.toList());
            List<RoleVo> roleVoList = loadRole(orgIds);
            organizationVo.setRoleVoList(roleVoList);
            organizationVo.setMenuVOList(loadMenuNoButton(roleVoList));
            organizationVo.setRoleIds(organizationVo.getRoleVoList() == null ? null : organizationVo.getRoleVoList().stream().map(RoleVo::getId).collect(Collectors.toList()));
            return organizationVo;
        }
        return null;
    }

    @Override
    public OrganizationVo findAllByIdNoResource(Long id) {
        Organization organization = getByIdCache(id);
        if (organization != null) {
            String code = organization.getCode();
            OrganizationDTO organizationDTO = new OrganizationDTO();
            //查询子集组织
            List<OrganizationOrgTypeEnum> orgTypeList = queryChildType(organization.getOrgType());
            orgTypeList.add(organization.getOrgType());
            organizationDTO.setOrgTypeList(orgTypeList);
            organizationDTO.setCode(code);
            //查询子节点
            List<Organization> childOrganizationList = queryAllOfCode(organizationDTO);
            if (childOrganizationList != null && !childOrganizationList.isEmpty()) {
                List<OrganizationVo> organizationVoList = doToVos(childOrganizationList);
                OrganizationVo organizationVo = loadTree(code, organizationVoList);
                //将角色加载进去
//                List<Long> orgIds = organizationVoList.stream().map(OrganizationVo::getId).collect(Collectors.toList());
//                List<RoleVo> roleVoList = loadRole(orgIds);
//                organizationVo.setRoleVoList(roleVoList);
//                organizationVo.setMenuVOList(loadMenu(roleVoList));
//                organizationVo.setFunctionVOList(loadFunction(roleVoList));
//                organizationVo.setRoleIds(organizationVo.getRoleVoList() == null ? null : organizationVo.getRoleVoList().stream().map(RoleVo::getId).collect(Collectors.toList()));
                return organizationVo;
            }
        }
        return null;
    }

    @Override
    public List<OrganizationVo> queryOrgNoResource(List<Organization> organizationList) {
        if (organizationList == null || organizationList.isEmpty()) {
            return null;
        }
        List<Long> orgIds = organizationList.stream().map(Organization::getId).collect(Collectors.toList());
        List<OrganizationVo> organizationVoList = new ArrayList<>();
        //将组织的角色全部查询出来
        Map<Long, List<RoleVo>> roleOfMap = loadRoleOfMap(orgIds);
        for (Organization organization : organizationList) {
            OrganizationVo organizationVo = new OrganizationVo();
            BeanUtils.copyProperties(organization, organizationVo);
            organizationVo.setId(organization.getId());
            List<RoleVo> roleVoList = roleOfMap.get(organization.getId());
            if (roleVoList != null && !roleVoList.isEmpty()) {
                organizationVo.setRoleVoList(roleVoList);
            }
            organizationVoList.add(organizationVo);
        }
        return organizationVoList;
    }

    @Override
    public OrganizationVo findMenuOrFunctionById(Long orgId) {
        Organization organization = getByIdCache(orgId);
        if (organization != null) {
            OrganizationVo organizationVo = new OrganizationVo();
            BeanUtils.copyProperties(organization, organizationVo);
            //将角色加载进去
            List<RoleVo> roleVoList = loadRole(Arrays.asList(orgId));
            organizationVo.setRoleVoList(roleVoList);
            organizationVo.setMenuVOList(loadMenuNoButton(roleVoList));
            organizationVo.setRoleIds(organizationVo.getRoleVoList() == null ? null : organizationVo.getRoleVoList().stream().map(RoleVo::getId).collect(Collectors.toList()));
            return organizationVo;
        }
        return null;
    }


    @Override
    public Organization queryOrgOfType(OrganizationOrgTypeEnum type, Long parentOrgId) {
        Organization organization = new Organization();
        if (parentOrgId != null) {
            Organization parentOrganization = getByIdCache(parentOrgId);
            organization.setCode(parentOrganization.getCode());
        } else {
            organization.setOrgType(type);
        }
        List<Organization> organizationList = listOfOrganization(organization, null);
        if (organizationList != null && !organizationList.isEmpty()) {
            //如果多个，取顶级组织
            if (organizationList.size() == 1) {
                return organizationList.get(0);
            }
            //清洗数据
            if (ContextUtil.getTeamId() != null) {
                organizationList = organizationList.stream().filter(s -> ContextUtil.getTeamId().equals(s.getTeamId())).collect(Collectors.toList());
            } else {
                organizationList = organizationList.stream().filter(s -> s.getTeamId() == null).collect(Collectors.toList());
            }
            if (CollectionUtil.isEmpty(organizationList)) {
                return null;
            }
            List<String> codeList = organizationList.stream().map(Organization::getCode).sorted(Comparator.comparingInt(String::length)).collect(Collectors.toList());
            String code = codeList.get(0);
            for (Organization organization1 : organizationList) {
                if (organization1.getCode().equals(code)) {
                    return organization1;
                }
            }
        }
        return null;
    }

    @Override
    public Organization queryOrgOfTypeAndResource(OrganizationOrgTypeEnum type, Long resourceId, ResourceOrganizationResourceTypeEnum resourceType) {
        ResourceOrganization resourceOrganization = new ResourceOrganization();
        resourceOrganization.setResourceId(resourceId);
        if (resourceType != null) {
            resourceOrganization.setResourceType(resourceType);
        }
        List<ResourceOrganization> resourceOrganizationList = resourceOrganizationService.listOfResourceOrganization(resourceOrganization, null, null);
        List<Long> orgIds = null;
        if (resourceOrganizationList == null || resourceOrganizationList.isEmpty()) {
            return null;
        }
        orgIds = resourceOrganizationList.stream().map(ResourceOrganization::getOrganizationId).collect(Collectors.toList());
        Organization organization = new Organization();
        organization.setOrgType(type);
        List<Organization> organizationList = listOfOrganization(organization, orgIds);
        if (organizationList != null && !organizationList.isEmpty()) {
            return organizationList.get(0);
        }
        return null;
    }

    @Override
    public List<Organization> queryOrgTypeOfParent(String parentCode, OrganizationOrgTypeEnum type) {
        //查询全部子节点
        OrganizationDTO organizationDTO = new OrganizationDTO();
        organizationDTO.setCode(parentCode);
        organizationDTO.setOrgType(type);
        List<Organization> childOrganizationList = queryAllOfCode(organizationDTO);
        if (childOrganizationList != null && !childOrganizationList.isEmpty()) {
            return childOrganizationList.stream().filter(s -> s.getOrgType().equals(type)).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public List<Organization> queryOrgNameOfParent(String parentCode, String orgName) {
        //查询全部子节点
        OrganizationDTO organizationDTO = new OrganizationDTO();
        organizationDTO.setCode(parentCode);
        organizationDTO.setName(orgName);
        List<Organization> childOrganizationList = queryAllOfCode(organizationDTO);
        if (childOrganizationList != null && !childOrganizationList.isEmpty()) {
            return childOrganizationList.stream().filter(s -> s.getName().equals(orgName)).collect(Collectors.toList());
        }
        return null;
    }

    @Override
    public Organization verifyResourceExistOfOrg(OrganizationDTO organizationDTO) {
        if (organizationDTO.getOrgId() == null || organizationDTO.getResourceId() == null) {
            return null;
        }
        //查询资源
        List<ResourceOrganization> resourceOrganizationList = resourceOrganizationService.findResource(organizationDTO.getResourceId());
        if (resourceOrganizationList == null || resourceOrganizationList.isEmpty()) {
            return null;
        }
        List<Long> resourceOrgIds = resourceOrganizationList.stream().map(ResourceOrganization::getOrganizationId).collect(Collectors.toList());
        //查询节点
        List<Organization> organizationList = listOfOrganization(null, Arrays.asList(organizationDTO.getOrgId()));
        if (organizationList == null || organizationList.isEmpty()) {
            return null;
        }
        Organization organization = organizationList.get(0);
        //是否是该组织
        if (resourceOrgIds.contains(organization.getId())) {
            return organization;
        }
        //没有，则找寻子节点组织
        OrganizationDTO organizationDTO1 = new OrganizationDTO();
        organizationDTO1.setCode(organization.getCode());
        List<Organization> childOrganizationList = queryAllOfCode(organizationDTO1);
        if (childOrganizationList != null && !childOrganizationList.isEmpty()) {
            for (Organization organization1 : childOrganizationList) {
                if (resourceOrgIds.contains(organization1.getId())) {
                    return organization;
                }
            }
        }
        return null;
    }

    @Override
    public List<Long> queryRoleOfResourceId(Long resourceId) {
        //查询资关联的组织id
        List<ResourceOrganization> resourceOrganizationList = resourceOrganizationService.findResource(resourceId);
        if (resourceOrganizationList != null && !resourceOrganizationList.isEmpty()) {
            List<Long> orgIds = resourceOrganizationList.stream().map(ResourceOrganization::getOrganizationId).collect(Collectors.toList());
            //组织关联的角色
            List<OrganizationRole> organizationRoleList = organizationRoleService.findOfOrg(orgIds);
            if (organizationRoleList != null && !organizationRoleList.isEmpty()) {
                return organizationRoleList.stream().map(OrganizationRole::getRoleId).collect(Collectors.toList());
            }
        }
        return null;
    }

    @Override
    public List<Long> queryOrgOfResourceId(Long resourceId, Long orgId) {
        Organization organization = getByIdCache(orgId);
        if (organization != null) {
            String code = organization.getCode();
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setCode(code);
            List<Organization> childOrganizationList = queryAllOfCode(organizationDTO);
            if (childOrganizationList == null || childOrganizationList.isEmpty()) {
                childOrganizationList = new ArrayList<>();
            }
            childOrganizationList.add(organization);
            List<Long> orgIds = childOrganizationList.stream().map(Organization::getId).collect(Collectors.toList());
            ResourceOrganization resourceOrganization = new ResourceOrganization();
            resourceOrganization.setResourceId(resourceId);
            List<ResourceOrganization> resourceOrganizationList = resourceOrganizationService.listOfResourceOrganization(resourceOrganization, orgIds, null);
            if (resourceOrganizationList != null && !resourceOrganizationList.isEmpty()) {
                return resourceOrganizationList.stream().map(ResourceOrganization::getOrganizationId).collect(Collectors.toList());
            }
        }
        return null;
    }

    @Override
    public Map<Long, List<Organization>> queryOrgVoOfResourceId(List<Long> resourceIds, List<Long> orgIds) {
        Map<Long, List<Organization>> result = new HashMap<>();
        for (Long orgId : orgIds) {
            Organization organization = getByIdCache(orgId);
            if (organization != null) {
                OrganizationDTO organizationDTO = new OrganizationDTO();
                organizationDTO.setCode(organization.getCode());
                List<Organization> childOrganizationList = queryAllOfCode(organizationDTO);
                if (childOrganizationList == null || childOrganizationList.isEmpty()) {
                    childOrganizationList = new ArrayList<>();
                }
                //全部组织
                childOrganizationList.add(organization);
                //查询资源与组织的关联数据
                List<ResourceOrganization> resourceOrganizationList = resourceOrganizationService.listOfResourceOrganization(null, childOrganizationList.stream().map(Organization::getId).collect(Collectors.toList()), resourceIds);
                if (resourceOrganizationList != null && !resourceOrganizationList.isEmpty()) {
                    for (ResourceOrganization resourceOrganization : resourceOrganizationList) {
                        List<Organization> organizationList = new ArrayList<>();
                        for (Organization organization1 : childOrganizationList) {
                            if (resourceOrganization.getOrganizationId().equals(organization1.getId())) {
                                organizationList.add(organization1);
                            }
                        }
                        result.put(resourceOrganization.getResourceId(), organizationList);
                    }
                }
            }
        }
        return result;
    }

    @Override
    public R addResourceOfOrgIds(Long resourceId, List<Long> orgIds, ResourceOrganizationResourceTypeEnum resourceType) {
        List<ResourceOrganization> resourceOrganizationList = resourceOrganizationService.listOfResourceOrganization(null, orgIds, Arrays.asList(resourceId));
        if (resourceOrganizationList != null && !resourceOrganizationList.isEmpty()) {
            List<Long> orgIds2 = resourceOrganizationList.stream().map(ResourceOrganization::getOrganizationId).collect(Collectors.toList());
            //去除已经存在的组织
            orgIds.removeAll(orgIds2);

        }
        if (orgIds != null && !orgIds.isEmpty()) {
            List<Organization> organizationList = listOfOrganization(null, orgIds);
            if (organizationList != null && !organizationList.isEmpty()) {
                for (Organization organization : organizationList) {
                    //添加资源
                    ResourceOrganizationSaveDTO resourceOrganizationSaveDTO = new ResourceOrganizationSaveDTO();
                    resourceOrganizationSaveDTO.setResourceId(resourceId);
                    resourceOrganizationSaveDTO.setResourceType(resourceType);
                    resourceOrganizationSaveDTO.setOrganizationId(organization.getId());
                    resourceOrganizationService.createResource(resourceOrganizationSaveDTO);
                }
            }
        }
        return R.success();
    }

    @Override
    public R delResource(Long resourceId, Long orgId) {
        Organization organization = getByIdCache(orgId);
        if (organization != null) {
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setCode(organization.getCode());
            List<Organization> childOrganizationList = queryAllOfCode(organizationDTO);
            if (childOrganizationList == null || childOrganizationList.isEmpty()) {
                childOrganizationList = new ArrayList<>();
            }
            childOrganizationList.add(organization);
            List<Long> orgIds = childOrganizationList.stream().map(Organization::getId).collect(Collectors.toList());
            List<ResourceOrganization> resourceOrganizationList = resourceOrganizationService.listOfResourceOrganization(null, orgIds, Arrays.asList(resourceId));
            if (resourceOrganizationList != null && !resourceOrganizationList.isEmpty()) {
                for (ResourceOrganization resourceOrganization : resourceOrganizationList) {
                    resourceOrganization.setIsDeleted(BusinessConstant.DELETE_YES);
                    resourceOrganizationService.updateById(resourceOrganization);
                }
            }
        }
        return R.success();
    }


    /**
     * 加载角色信息
     *
     * @param orgIds
     */
    @Override
    public List<RoleVo> loadRole(List<Long> orgIds) {
        if (orgIds == null || orgIds.isEmpty()) {
            return null;
        }
//        //通过节点查询所关联的资源，在通过资源查询所有关联的节点，最后拿到所有节点的角色
//        List<ResourceOrganization> resourceOrganizationList = resourceOrganizationService.assembleOrgOfresource(orgIds);
//        if (resourceOrganizationList != null && !resourceOrganizationList.isEmpty()) {
//            orgIds = resourceOrganizationList.stream().map(ResourceOrganization::getOrganizationId).collect(Collectors.toList());
//        }
        //批量查询节点的资源和用户信息
        List<OrganizationRole> orgRoleList = organizationRoleService.findOfOrg(orgIds);
        if (orgRoleList != null && !orgRoleList.isEmpty()) {
            Set<Long> roleIds = orgRoleList.stream().map(OrganizationRole::getRoleId).collect(Collectors.toSet());
            return roleService.findAllById(new ArrayList<>(roleIds));
        }
        return null;
    }

    @Override
    public Map<Long, List<RoleVo>> loadRoleOfMap(List<Long> orgIds) {
        if (orgIds == null || orgIds.isEmpty()) {
            return null;
        }
        Map<Long, List<RoleVo>> result = new HashMap<>();
        //批量查询节点的资源和用户信息
        List<OrganizationRole> orgRoleList = organizationRoleService.findOfOrg(orgIds);
        if (orgRoleList != null && !orgRoleList.isEmpty()) {
            Set<Long> roleIds = orgRoleList.stream().map(OrganizationRole::getRoleId).collect(Collectors.toSet());
            List<RoleVo> roleVoList = roleService.findAllById(new ArrayList<>(roleIds));
            //组装组织角色信息
            for (Long orgId : orgIds) {
                if (roleVoList == null || roleVoList.isEmpty()) {
                    result.put(orgId, null);
                } else {
                    //过滤角色id
                    List<Long> roleIdList = orgRoleList.stream().filter(s -> s.getOrganizationId().equals(orgId)).map(OrganizationRole::getRoleId).collect(Collectors.toList());
                    //角色id查询角色
                    if (roleIdList != null && !roleIdList.isEmpty()) {
                        result.put(orgId, roleVoList.stream().filter(s -> roleIdList.contains(s.getId())).collect(Collectors.toList()));
                    }
                }
            }
        }
        return result;
    }

    /**
     * 加载菜单信息
     *
     * @param roleVoList
     */
    @Override
    public List<MenuVO> loadMenuNoButton(List<RoleVo> roleVoList) {
        if (roleVoList == null || roleVoList.isEmpty()) {
            return null;
        }
        List<MenuRole> menuRoleList = loadMenuRole(roleVoList);
        if (menuRoleList != null && !menuRoleList.isEmpty()) {
            List<Long> menuIds = menuRoleList.stream().map(MenuRole::getMenuId).collect(Collectors.toList());
            MenuDTO menuDTO = new MenuDTO();
            menuDTO.setMenuIds(menuIds);
            if (StringUtils.isNotBlank(ContextUtil.getMenuAffiliation())) {
                menuDTO.setAffiliation(MenuAffiliationEnum.get(ContextUtil.getMenuAffiliation()));
            }
            if (StringUtils.isNotBlank(ContextUtil.getMenuScene())) {
                menuDTO.setScene(MenuSceneEnum.get(ContextUtil.getMenuScene()));
            }
            R<List<MenuVO>> r = projectCoreServiceFeign.findAllByChildIdNoButton(menuDTO);
            if (r.getCode() == SUCCESS_CODE) {
                return r.getData();
            }
        }
        return null;
    }

    @Override
    public List<MenuVO> loadMenuAll(List<RoleVo> roleVoList) {
        if (roleVoList == null || roleVoList.isEmpty()) {
            return null;
        }
        List<MenuRole> menuRoleList = loadMenuRole(roleVoList);
        if (menuRoleList != null && !menuRoleList.isEmpty()) {
            List<Long> menuIds = menuRoleList.stream().map(MenuRole::getMenuId).collect(Collectors.toList());
            MenuDTO menuDTO = new MenuDTO();
            menuDTO.setMenuIds(menuIds);
            if (StringUtils.isNotBlank(ContextUtil.getMenuAffiliation())) {
                menuDTO.setAffiliation(MenuAffiliationEnum.get(ContextUtil.getMenuAffiliation()));
            }
            if (StringUtils.isNotBlank(ContextUtil.getMenuScene())) {
                menuDTO.setScene(MenuSceneEnum.get(ContextUtil.getMenuScene()));
            }
            R<List<MenuVO>> r = projectCoreServiceFeign.findAllByChildId(menuDTO);
            if (r.getCode() == SUCCESS_CODE) {
                return r.getData();
            }
        }
        return null;
    }


    /**
     * 加载菜单的权限标识信息
     *
     * @param roleVoList
     */
    @Override
    public Map<String, List<String>> loadMenuPermission(Long userId,List<RoleVo> roleVoList) {
        if (roleVoList == null || roleVoList.isEmpty()) {
            return null;
        }
        Map<String, List<String>> result = new HashMap<>();

        List<MenuRole> menuRoleList = loadMenuRole(roleVoList);
        if (menuRoleList != null && !menuRoleList.isEmpty()) {
            List<Long> menuIds = menuRoleList.stream().map(MenuRole::getMenuId).collect(Collectors.toList());
            MenuDTO menuDTO = new MenuDTO();
            menuDTO.setMenuIds(menuIds);
            if (StringUtils.isNotBlank(ContextUtil.getMenuAffiliation())) {
                menuDTO.setAffiliation(MenuAffiliationEnum.get(ContextUtil.getMenuAffiliation()));
            }
            if (StringUtils.isNotBlank(ContextUtil.getMenuScene())) {
                menuDTO.setScene(MenuSceneEnum.get(ContextUtil.getMenuScene()));
            }
            //权限标识
            R<List<String>> premissionR = projectCoreServiceFeign.findPermissionAllByChildId(menuDTO);
            //接口标识
            R<List<String>> interfaceR = projectCoreServiceFeign.findInterfaceAllByChildId(menuDTO);
            if (premissionR.getCode() == SUCCESS_CODE) {
                result.put("premission", premissionR.getData());
                //添加到缓存
                CacheKey cacheKey = new PermissionCacheKeyBuilder().key(userId);
                cacheOps.set(cacheKey, premissionR.getData());
            }
            if (interfaceR.getCode() == SUCCESS_CODE) {
                result.put("interface", interfaceR.getData());
                String cachekeyName = (StringUtils.isNotBlank(ContextUtil.getSystemScene())?ContextUtil.getSystemScene():"")+userId;
                CacheKey cacheKey2 = new InterfaceCacheKeyBuilder().key(cachekeyName);
                cacheOps.set(cacheKey2, interfaceR.getData());
            }
        }
        return result;
    }

    @Override
    public Map<Long, List<MenuVO>> loadMenuOfMap(List<RoleVo> roleVoList) {
        if (roleVoList == null || roleVoList.isEmpty()) {
            return null;
        }
        Map<Long, List<MenuVO>> result = new HashMap<>();
        List<MenuRole> menuRoleList = loadMenuRole(roleVoList);
        if (menuRoleList != null && !menuRoleList.isEmpty()) {
            List<Long> menuIds = menuRoleList.stream().map(MenuRole::getMenuId).collect(Collectors.toList());
            MenuDTO menuDTO = new MenuDTO();
            menuDTO.setMenuIds(menuIds);
            if (StringUtils.isNotBlank(ContextUtil.getMenuAffiliation())) {
                menuDTO.setAffiliation(MenuAffiliationEnum.get(ContextUtil.getMenuAffiliation()));
            }
            if (StringUtils.isNotBlank(ContextUtil.getMenuScene())) {
                menuDTO.setScene(MenuSceneEnum.get(ContextUtil.getMenuScene()));
            }
            R<List<MenuVO>> r = projectCoreServiceFeign.findAllByChildId(menuDTO);
            if (r.getCode() == SUCCESS_CODE) {
                List<MenuVO> menuVOList = r.getData();
                //组装角色菜单信息
                for (RoleVo roleVo : roleVoList) {
                    if (menuVOList == null || menuVOList.isEmpty()) {
                        result.put(roleVo.getId(), null);
                    } else {
                        //过滤菜单id
                        List<Long> menuIdList = menuRoleList.stream().filter(s -> s.getRoleId().equals(roleVo.getId())).map(MenuRole::getMenuId).collect(Collectors.toList());
                        //菜单id查询菜单
                        if (menuIdList != null && !menuIdList.isEmpty()) {
                            result.put(roleVo.getId(), menuVOList.stream().filter(s -> menuIdList.contains(s.getId())).collect(Collectors.toList()));
                        }
                    }
                }
            }
        }
        return result;
    }


    @Override
    public List<MenuRole> loadMenuRole(List<RoleVo> roleVoList) {
        if (roleVoList == null || roleVoList.isEmpty()) {
            return null;
        }
        List<Long> roleIds = roleVoList.stream().map(RoleVo::getId).collect(Collectors.toList());
        List<MenuRole> menuRoleList = menuRoleService.list(null, null, roleIds);
        return menuRoleList;
    }


    @Override
    public R removeResourceUserOfOrg(List<Long> orgIds) {
        //删除关联的资源
        resourceOrganizationService.delOfOrgIds(orgIds);
        userOrganizationService.delOfOrgIds(orgIds);
        return R.success();
    }

    @Override
    public void loadUserAndResource(List<OrganizationVo> organizationVoList) {
        if (organizationVoList != null && !organizationVoList.isEmpty()) {
            //抓取所有节点idz
            List<Long> orgIds = organizationVoList.stream().map(OrganizationVo::getId).collect(Collectors.toList());
            //批量查询节点的资源和用户信息
            List<ResourceOrganizationVo> resourceOrganizationList = resourceOrganizationService.queryResource(orgIds);
            List<UserOrganizationVo> userOrganizationVoList = userOrganizationService.queryUserVoByOrg(orgIds);
            //将用户和资源加载进去
            for (OrganizationVo organizationVo : organizationVoList) {
                //定义list
                List<ResourceOrganizationVo> resourceOrganizationVos = new ArrayList<>();
                List<UserOrganizationVo> userOrganizationVoList1 = new ArrayList<>();

                if (resourceOrganizationList != null && !resourceOrganizationList.isEmpty()) {
                    for (ResourceOrganizationVo resourceOrganizationVo : resourceOrganizationList) {
                        if (organizationVo.getId().equals(resourceOrganizationVo.getOrganizationId())) {
                            resourceOrganizationVos.add(resourceOrganizationVo);
                        }
                    }
                }
                if (userOrganizationVoList != null && !userOrganizationVoList.isEmpty()) {
                    for (UserOrganizationVo userOrganizationVo : userOrganizationVoList) {
                        if (organizationVo.getId().equals(userOrganizationVo.getOrganizationId())) {
                            userOrganizationVoList1.add(userOrganizationVo);
                        }
                    }
                }
                if (resourceOrganizationVos != null && !resourceOrganizationVos.isEmpty()) {
                    organizationVo.setResourceOrganizationVo(resourceOrganizationVos);
                }
                if (userOrganizationVoList1 != null && !userOrganizationVoList1.isEmpty()) {
                    organizationVo.setUserOrganizationVoList(userOrganizationVoList1);
                }
            }
        }
    }


    @Override
    public List<Organization> listOfOrganization(Organization organization, List<Long> ids) {
        return ((OrganizationService) AopContext.currentProxy()).listOfOrganizationOfCache(organization, ids);
    }

    @Override
//    @Cache(key = "#hash(#args)")
    @Cache(key = "",
            magic = @Magic(
                    key = "{{'parentId', #args[0]?.parentId},{'id', #args[0]?.id},{'code', #args[0]?.code,'like'}," +
                            "{'huaweiOrgId', #args[0]?.huaweiOrgId},{'orgType', #args[0]?.orgType},{'name', #args[0]?.name}" +
                            ",{'vestType', #args[0]?.vestType},{'id', #args[1]}}"))
    public List<Organization> listOfOrganizationOfCache(Organization organization, List<Long> ids) {
        //查询
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        if (organization != null) {
            if (organization.getParentId() != null) {
                queryWrapper.lambda().eq(Organization::getParentId, organization.getParentId());
            }

            if (StringUtils.isNotBlank(organization.getHuaweiOrgId())) {
                queryWrapper.lambda().eq(Organization::getHuaweiOrgId, organization.getHuaweiOrgId());
            }


            if (organization.getId() != null) {
                queryWrapper.lambda().eq(Organization::getId, organization.getId());
            }
            if (StringUtils.isNotBlank(organization.getCode())) {
                queryWrapper.lambda().likeRight(Organization::getCode, organization.getCode());
            }
            if (organization.getOrgType() != null) {
                queryWrapper.lambda().eq(Organization::getOrgType, organization.getOrgType().getCode());
            }
            if (organization.getName() != null) {
                queryWrapper.lambda().eq(Organization::getName, organization.getName());
            }
            if (organization.getVestType() != null) {
                queryWrapper.lambda().eq(Organization::getVestType, organization.getVestType());
            }
        }
        if (ids != null && !ids.isEmpty()) {
            queryWrapper.lambda().in(Organization::getId, ids);
        }
        queryWrapper.lambda().eq(Organization::getIsDeleted, BusinessConstant.DELETE_NO);
        //排序查询
        queryWrapper.orderByAsc("sequence");
        List<Organization> organizationList = list(queryWrapper);
        return organizationList;
    }

    @Override
    public R addOrgRole(Long orgId, List<Long> roleIds, boolean isConduction) {
        Organization organization = getByIdCache(orgId);
        if (organization == null) {
            return R.fail(NODE_NO);
        }
        if (roleIds != null && !roleIds.isEmpty()) {
            OrganizationRole orgRole = new OrganizationRole();
            orgRole.setOrganizationId(orgId);
            List<OrganizationRole> orgRoleList = organizationRoleService.list(orgRole, null, roleIds);
            //剔除已经存在的
            if (orgRoleList != null && !orgRoleList.isEmpty()) {
                List<Long> oldRoleIds = orgRoleList.stream().map(OrganizationRole::getRoleId).collect(Collectors.toList());
                roleIds.removeAll(oldRoleIds);
            }

            if (roleIds != null && !roleIds.isEmpty()) {
                List<Organization> organizationList = new ArrayList<>();
                if (isConduction) {
                    OrganizationDTO organizationDTO = new OrganizationDTO();
                    organizationDTO.setCode(organization.getCode());
                    organizationList = queryAllOfCode(organizationDTO);
                } else {
                    organizationList.add(organization);
                }
                organizationRoleService.addOrgRole(organizationList, roleIds);
            }
        }
        return R.success();
    }

    @Override
    public R verifyMenuIsOver(Long parentOrgId, List<Long> menuIds) {
        if (BusinessConstant.parentId.equals(parentOrgId) || menuIds == null || menuIds.isEmpty()) {
            return R.success();
        }
        //查询组织信息
        List<RoleVo> roleVoList = loadRole(Arrays.asList(parentOrgId));
        if (roleVoList == null || roleVoList.isEmpty()) {
            //菜单超出范围
            return R.fail(MEUN_MORE);
        }
        //查询角色菜单关联信息
        List<MenuRole> menuRoleList = loadMenuRole(roleVoList);
        if (menuRoleList == null || menuRoleList.isEmpty()) {
            //菜单超出范围
            return R.fail(MEUN_MORE);
        }
        //校验菜单是否超出范围
        if (menuRoleList != null && !menuRoleList.isEmpty()) {
            List<Long> userMenuIds = menuRoleList.stream().map(MenuRole::getMenuId).collect(Collectors.toList());
            for (Long menuId : menuIds) {
                if (!userMenuIds.contains(menuId)) {
                    //菜单超出范围
                    return R.fail(MEUN_MORE);
                }
            }
            return R.success();
        }
        //菜单超出范围
        return R.fail(MEUN_MORE);
    }

    @Override
    public R updOrgRole(Long orgId, List<Long> roleIds, boolean isConduction) {
        Organization organization = getByIdCache(orgId);
        if (organization == null) {
            return R.fail(NODE_NO);
        }
        //先删除组织下的角色
        removeOrgRole(orgId);
        //添加组织的角色
        addOrgRole(orgId, roleIds, isConduction);
        return R.success();
    }

    @Override
    public R removeOrgRole(Long orgId, List<Long> roleIds, boolean isConduction) {
        Organization organization = getByIdCache(orgId);
        if (organization == null) {
            return R.success();
        }
        if (roleIds != null && !roleIds.isEmpty()) {
            List<Organization> organizationList = new ArrayList<>();
            if (isConduction) {
                OrganizationDTO organizationDTO = new OrganizationDTO();
                organizationDTO.setCode(organization.getCode());
                organizationList = queryAllOfCode(organizationDTO);
            } else {
                organizationList.add(organization);
            }
            organizationRoleService.removeOrgRole(organizationList, roleIds);
        }
        return R.success();
    }

    @Override
    public R removeOrgRole(Long orgId) {
        Organization organization = getByIdCache(orgId);
        if (organization == null) {
            return R.success();
        }
        //查询节点下的角色关系
        List<OrganizationRole> organizationRoleList = organizationRoleService.findOfOrg(Arrays.asList(orgId));
        if (organizationRoleList != null && !organizationRoleList.isEmpty()) {
            //过滤到角色
            List<Long> roleIds = organizationRoleList.stream().map(OrganizationRole::getRoleId).collect(Collectors.toList());
            OrganizationDTO organizationDTO = new OrganizationDTO();
            organizationDTO.setCode(organization.getCode());
            organizationRoleService.removeOrgRole(queryAllOfCode(organizationDTO), roleIds);
        }
        return R.success();
    }

    @Override
    public R removeOfRole(List<Long> roleIds) {
        return organizationRoleService.removeOfRole(roleIds);
    }

    @Override
    public List<MenuVO> loadMenu(List<RoleVo> roleVoList) {
        if (roleVoList == null || roleVoList.isEmpty()) {
            return null;
        }
        List<MenuRole> menuRoleList = loadMenuRole(roleVoList);
        if (menuRoleList != null && !menuRoleList.isEmpty()) {
            List<Long> menuIds = menuRoleList.stream().map(MenuRole::getMenuId).collect(Collectors.toList());
            MenuDTO menuDTO = new MenuDTO();
            menuDTO.setMenuIds(menuIds);
            if (StringUtils.isNotBlank(ContextUtil.getMenuAffiliation())) {
                menuDTO.setAffiliation(MenuAffiliationEnum.get(ContextUtil.getMenuAffiliation()));
            }
            if (StringUtils.isNotBlank(ContextUtil.getMenuScene())) {
                menuDTO.setScene(MenuSceneEnum.get(ContextUtil.getMenuScene()));
            }
            R<List<MenuVO>> r = projectCoreServiceFeign.findAllByChildIdNoButton(menuDTO);
            if (r.getCode() == SUCCESS_CODE) {
                return r.getData().get(0).getChildVoList();
            }
        }
        return null;
    }


    @Override
    public List<Map> loadUserPermission(List<Long> userIdList) {
        if (userIdList == null || userIdList.isEmpty()) {
            return null;
        }
        List<Map> result = new ArrayList<>();
        for (Long userId : userIdList) {
            Map map = new HashMap();
            UserOrganization userOrganization = new UserOrganization();
            userOrganization.setUserId(userId);
            List<UserOrganization> userOrganizationList = userOrganizationService.listOfUserOrganization(userOrganization, null, null);
            if (userOrganizationList != null && !userOrganizationList.isEmpty()) {
                //将角色加载进去
                List<Long> orgIds = userOrganizationList.stream().map(UserOrganization::getOrganizationId).collect(Collectors.toList());
                List<RoleVo> roleVoList = loadRole(orgIds);
//                List<String> permissionList = loadMenuPermission(roleVoList);
                Map<String, List<String>> resultMap = loadMenuPermission(userId,roleVoList);
                map.put("userId", userId);
                map.put("permissionList", resultMap.get("premission"));
                map.put("interfaceList", resultMap.get("interface"));
                result.add(map);
//                System.out.println(JSON.toJSONString(map));
            }
        }
        return result;
    }

    @Override
    public List<Map> loadUserPermissionOfOrg(List<Long> orgIdList) {
        List<UserOrganization> userOrganizationList = userOrganizationService.listOfUserOrganization(null, null, orgIdList);
        if (userOrganizationList != null && !userOrganizationList.isEmpty()) {
            List<Long> userIdList = userOrganizationList.stream().map(UserOrganization::getUserId).collect(Collectors.toList());
            return loadUserPermission(userIdList);
        }
        return null;
    }

    @Override
    public List<Map> loadUserPermissionOfRole(List<Long> roleIdList) {
        List<OrganizationRole> organizationRoleList = organizationRoleService.findOfRole(roleIdList);
        if (organizationRoleList != null && !organizationRoleList.isEmpty()) {
            List<Long> orgIdList = organizationRoleList.stream().map(OrganizationRole::getOrganizationId).collect(Collectors.toList());
            return loadUserPermissionOfOrg(orgIdList);
        }
        return null;
    }

    @Override
    public Boolean isPermission(Long userId, String[] permission, String[] classPermission) {
        CacheKey cacheKey = new PermissionCacheKeyBuilder().key(userId);
        List<String> permissionList = cacheOps.get(cacheKey);
        if (permissionList == null || permissionList.isEmpty()) {
            //重新加载信息
            List<Map> maps = loadUserPermission(Arrays.asList(userId));
            if (maps != null && !maps.isEmpty()) {
                for (Map map : maps) {
                    if (((Long) map.get("userId")).equals(userId)) {
                        permissionList = (List<String>) map.get("permissionList");
                    }
                }
            }
        }

        //判断是否有权限
        if (permissionList != null && !permissionList.isEmpty()) {
            if (permission == null && classPermission != null) {
                //则在类上检验是否有权限
                String classPremissStr = classPermission[0];
                for (String s : permissionList) {
                    if (s.indexOf(classPremissStr) > -1) {
                        //有权限
                        return true;
                    }
                }

            }

            for (String s : permission) {
                if (permissionList.contains(s)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public List<Long> queryOrgChildId(List<Long> orgIds) {
        OrganizationDTO organizationDTO = new OrganizationDTO();
        List<Organization> organizationList = listOfOrganization(null, orgIds);
        if (organizationList != null && !organizationList.isEmpty()) {
            organizationDTO.setCodes(organizationList.stream().map(Organization::getCode).collect(Collectors.toList()));
        }
        List<Organization> childOrganizationList = queryAllOfCode(organizationDTO);
        return childOrganizationList.stream().map(Organization::getId).collect(Collectors.toList());

    }

    @Override
    public Map<Long, List<Organization>> queryOrgOfUserId(List<Long> userIds) {
        Map<Long, List<Organization>> result = new HashMap<>();
        List<UserOrganization> userOrganizationList = userOrganizationService.listOfUserOrganization(null, userIds, null);
        if (userOrganizationList == null || userOrganizationList.isEmpty()) {
            return null;
        }
        List<Long> orgIds = userOrganizationList.stream().map(UserOrganization::getOrganizationId).collect(Collectors.toList());
        List<Organization> organizationList = listOfOrganization(null, orgIds);
        if (organizationList == null || organizationList.isEmpty()) {
            return null;
        }
        for (Long userId : userIds) {
            List<Long> orgIdOfUserId = userOrganizationList.stream().filter(s -> s.getUserId().equals(userId)).map(UserOrganization::getOrganizationId).collect(Collectors.toList());
            if (orgIdOfUserId == null || orgIdOfUserId.isEmpty()) {
                result.put(userId, null);
            } else {
                result.put(userId, organizationList.stream().filter(s -> orgIdOfUserId.contains(s.getId())).collect(Collectors.toList()));
            }
        }
        return result;
    }

    @Override
    public List<Long> queryMenuIdOfUser(Long userId) {
        UserOrganization userOrganization = new UserOrganization();
        userOrganization.setUserId(userId);
        List<RoleVo> roleVoList = new ArrayList<>();
        //查询用户角色
        List<UserRole> userRoleList = userRoleService.findOfUser(Arrays.asList(userId));
        if (userRoleList != null && !userRoleList.isEmpty()) {
            roleVoList.addAll(roleService.doToVos(roleService.listByIds(userRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList()))));
        }
        List<UserOrganization> userOrganizationList = userOrganizationService.listOfUserOrganization(userOrganization, null, null);
        if (userOrganizationList != null && !userOrganizationList.isEmpty()) {
            //将角色加载进去
            List<Long> orgIds = userOrganizationList.stream().map(UserOrganization::getOrganizationId).collect(Collectors.toList());
            //加载角色
            List<RoleVo> roleVoList1 = loadRole(orgIds);
            if (roleVoList1 != null && !roleVoList1.isEmpty()) {
                roleVoList.addAll(roleVoList1);
            }
        }
        List<MenuVO> menuVOList = loadMenuAll(roleVoList);
        if (menuVOList != null && !menuVOList.isEmpty()) {
            List<Long> menuIds = new ArrayList<>();
            for (MenuVO menuVO : menuVOList) {
                menuIds.add(menuVO.getId());
                menuIds.addAll(menuVO.getChildIdList());
            }
            return menuIds;
        }
        return null;
    }

    @Override
    public List<Organization> initOrgAndRole(OrganizationDTO organizationDTO) {
        log.info("initOrgAndRole is execute  params is {}",JSONObject.toJSONString(organizationDTO));
        //创建 角色
        //子系统id
//        ContextUtil.setSubSystemId(DataIsoLotionUtil.findSubSystemId(organizationDTO.getSubsystemList(), OrganizationOrgTypeEnum.P.getCode()));
        List<Role> roleList = roleService.initRole(organizationDTO);
        List<Organization> organizationList = initOrgOfProject(organizationDTO);
//        List<Organization> resourceOrganizationList = initOrgOfResource();
//        if (resourceOrganizationList != null && !resourceOrganizationList.isEmpty()) {
//            organizationList.addAll(resourceOrganizationList);
//        }
        //绑定组织和角色
        for (Organization organization : organizationList) {
            List<Long> roleIds = new ArrayList<>();
            for (Role role : roleList) {
                if (("_" + role.getRoleType().getCode().toLowerCase()).indexOf("_" + organization.getOrgType().getCode().toLowerCase() + "_admin") > -1) {
                    //匹配上，角色加入到组织
                    roleIds.add(role.getId());
                }
            }
            //设置组织角色的场景归属
            ContextUtil.setSystemScene(organization.getOrgType().getCode());
            if (roleIds.size() > 0) {
                //角色加入到组织
                addOrgRole(organization.getId(), roleIds, false);
            }


            //项目管理员角色占所有菜单
//            if (("_" + RoleRoleTypeEnum.P_ADMIN.getCode().toLowerCase()).indexOf("_" + organization.getOrgType().getCode().toLowerCase() + "_admin") > -1) {
//                RoleRoleTypeEnum roleRoleTypeEnum = RoleRoleTypeEnum.P_ADMIN;
//                QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
//                queryWrapper.lambda().eq(Role::getRoleType, roleRoleTypeEnum);
//                queryWrapper.lambda().eq(Role::getIsDeleted, BusinessConstant.DELETE_NO);
//                Role role = roleService.getOne(queryWrapper);
//                if (role != null) {
//                    R<List<Long>> listR = projectCoreServiceFeign.queryAllMenuId();
//                    if (SUCCESS_CODE == listR.getCode() && listR.getData() != null && !listR.getData().isEmpty()) {
//                        //角色加入到组织
//                        RoleDTO roleDTO = new RoleDTO();
//                        roleDTO.setId(role.getId());
//                        roleDTO.setMenuIds(listR.getData());
//                        roleService.reloadRoleRelationOfMenu(roleDTO);
//                    }
//                }
//            }


        }

        return organizationList;
    }

    @Override
    public List<Organization> initOrgOfProject(OrganizationDTO organizationDTO) {
        return initOrgData(OrganizationVestTypeEnum.P, organizationDTO);
    }

    @Override
    public List<Organization> initOrgOfResource() {
//        return initOrgData(OrganizationVestTypeEnum.R);
        return null;
    }


    /**
     * 初始化组织数据
     *
     * @param organizationVestType 组织归属
     * @return
     */
    public List<Organization> initOrgData(OrganizationVestTypeEnum organizationVestType, OrganizationDTO organizationDTO) {
//        List<OrganizationOrgTypeEnum> organizationOrgTypeEnums = Arrays.asList(OrganizationOrgTypeEnum.values());
        //过滤掉不是项目的组织
//        organizationOrgTypeEnums = organizationOrgTypeEnums.stream().filter(s -> {
//            return ("_" + s.getCode()).indexOf("_" + organizationVestType.getCode() + "_") > -1 || organizationVestType.getCode().equals(s.getCode());
//        }).collect(Collectors.toList());
//        //排序
//        Collections.sort(organizationOrgTypeEnums, new Comparator<OrganizationOrgTypeEnum>() {
//            @Override
//            public int compare(OrganizationOrgTypeEnum o1, OrganizationOrgTypeEnum o2) {
//                // 返回值为int类型，大于0表示正序，小于0表示逆序
//                return o1.getCode().length() - o2.getCode().length();
//            }
//        });
        //初始化组织
        List<Organization> result = new ArrayList<>();
        for (OrganizationOrgTypeEnum organizationOrgTypeEnum : OrganizationOrgTypeEnum.values()) {
//            需要按子系统id隔离
//            ContextUtil.setSubSystemId(DataIsoLotionUtil.findSubSystemId(organizationDTO.getSubsystemList(), organizationOrgTypeEnum.getCode()));
            //是否包含系统
            if (DataIsoLotionUtil.findSubSystemId(organizationDTO.getSubsystemList(), organizationOrgTypeEnum.getCode()) == null) {
                continue;
            }
            if (ContextUtil.getSubSystemId() == null) {
                continue;
            }
            QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(Organization::getOrgType, organizationOrgTypeEnum);
            queryWrapper.lambda().eq(Organization::getIsDeleted, BusinessConstant.DELETE_NO);
            Organization updOrganization = getOne(queryWrapper);
            if (updOrganization != null) {
                updOrganization.setName(organizationOrgTypeEnum.getDesc());
                updOrganization.setVestType(organizationVestType);
                updateById(updOrganization);
                result.add(updOrganization);
            } else {
                Organization organization = new Organization();
                organization.setName(organizationOrgTypeEnum.getDesc());
                organization.setOrgType(organizationOrgTypeEnum);
//                organization.setParentId(parendId);
                organization.setVestType(organizationVestType);
                save(organization);
                result.add(organization);
            }
        }
        return result;
    }


    @Override
    public List<Organization> findResource(OrganizationOrgTypeEnum type, OrganizationVestTypeEnum vestType, Long parentOrgId, Long resourceId) {
        List<Long> orgIds = null;
        if (resourceId == null) {
            return null;
        }
        Organization organization = new Organization();
        if (type != null) {
            organization.setOrgType(type);
        }
        if (vestType != null) {
            organization.setVestType(vestType);
        }
        if (parentOrgId != null) {
            //有父级信息，则可直接定位到组织
            Organization parentOrganization = getByIdCache(parentOrgId);
            organization.setCode(parentOrganization.getCode());
        } else {
            //查询资源相关的组织id
            List<ResourceOrganization> resourceOrganizationList = resourceOrganizationService.findResource(resourceId);
            if (resourceOrganizationList == null || resourceOrganizationList.isEmpty()) {
                return null;
            }
            orgIds = resourceOrganizationList.stream().map(ResourceOrganization::getOrganizationId).collect(Collectors.toList());
        }
        List<Organization> organizationList = listOfOrganization(organization, orgIds);
        return organizationList;
    }

    @Override
    public R breakUseridOfOrg(Long orgId, List<Long> userIds) {
        if (userIds == null || userIds.isEmpty()) {
            return userOrganizationService.delOfOrgIds(Arrays.asList(orgId));
        }
        return userOrganizationService.removeUserOfOrg(orgId, userIds);

    }

    @Override
    public R addUseridOfOrg(Long orgId, List<Long> userIds, Integer isLeader) {
//        if (isLeader != null) {
//            Organization organization = getByIdCache(orgId);
//            if (organization != null) {
//                //处理组织负责人
//                assmbileUserIds(organization.getLeaderIds(), userIds, isLeader);
//            }
//        }

        return userOrganizationService.addUserOfOrg(orgId, userIds, isLeader);
    }

    /**
     * 组装负责人信息
     *
     * @param leaderIds
     * @param userIds
     * @param isLeader
     * @return
     */
    public Set<Long> assmbileUserIds(String leaderIds, List<Long> userIds, Integer isLeader) {
        Set<Long> resultUserIds = new HashSet<>();
        if (StringUtils.isNotBlank(leaderIds)) {
            resultUserIds = new HashSet<>(JSONArray.parseArray(leaderIds, Long.class));
        }
        if (CollectionUtil.isEmpty(userIds) || userIds.size() == 0 || isLeader == null) {
            return resultUserIds;
        }
        if (isLeader == BusinessConstant.YES) {
            for (Long userId : userIds) {
                resultUserIds.add(userId);
            }

        } else if (isLeader == BusinessConstant.NO) {
            for (Long userId : userIds) {
                resultUserIds.remove(userId);
            }
        }
        return resultUserIds;
    }


    /**
     * 通过枚举查询父级id
     *
     * @param orgType
     * @return
     */
    public Long queryParentIdOfType(String orgType) {
        //找到OrganizationOrgTypeEnum
        boolean pan = true;
        while (pan) {
            if (orgType.lastIndexOf("_") > -1) {
                orgType = orgType.substring(0, orgType.lastIndexOf("_"));
            } else {
                pan = false;
                continue;
            }
            if (OrganizationOrgTypeEnum.get(orgType) != null) {
                pan = false;
            }
        }
        if (OrganizationOrgTypeEnum.get(orgType) == null) {
            return null;
        }
        //查询
        QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Organization::getIsDeleted, BusinessConstant.DELETE_NO);
        queryWrapper.lambda().eq(Organization::getOrgType, OrganizationOrgTypeEnum.get(orgType));
        Organization organization = getOne(queryWrapper);
        if (organization != null) {
            return organization.getId();
        }
        return null;
    }


    /**
     * 通过枚举查询子集组织
     *
     * @param organizationOrgTypeEnum
     * @return
     */
    public List<OrganizationOrgTypeEnum> queryChildType(OrganizationOrgTypeEnum organizationOrgTypeEnum) {
        List<OrganizationOrgTypeEnum> result = Arrays.asList(OrganizationOrgTypeEnum.values());
        result = result.stream().filter(s -> {
            return s.getCode().indexOf(organizationOrgTypeEnum.getCode() + "_") > -1;
        }).collect(Collectors.toList());
        result.add(OrganizationOrgTypeEnum.OTHER);
        return result;
    }

    @Override
    public OrganizationVo doToVo(Organization organization) {
        if (organization == null) {
            return null;
        }
        OrganizationVo organizationVo = new OrganizationVo();
        BeanUtils.copyProperties(organization, organizationVo);
        organizationVo.setId(organization.getId());
        return organizationVo;
    }

    @Override
    public List<OrganizationVo> doToVos(List<Organization> organizationList) {
        if (organizationList == null || organizationList.isEmpty()) {
            return null;
        }
        List<OrganizationVo> result = new ArrayList<>();
        for (Organization organization : organizationList) {
            result.add(doToVo(organization));
        }
        return result;
    }

    @Override
    public DataTreeVo assemblyTree(OrganizationVo organizationVo) {
        DataTreeVo dataTreeVo = new DataTreeVo();
        BeanUtils.copyProperties(organizationVo, dataTreeVo);
        dataTreeVo.setDataType("org");
        List<OrganizationVo> organizationVoList = new ArrayList<>();
        organizationVoList = assemblyTree(organizationVo.getChildVoList());

        List<DataTreeVo> dataTreeVos = new ArrayList<>();
        dataTreeVos = assemblyToDataTree(dataTreeVos, organizationVoList);
        dataTreeVo.setTreeChildVoList(dataTreeVos);
        return dataTreeVo;
    }

    @Override
    public HuaWeiOrganizationDTO sycnOrgOfCreate(HuaWeiOrganizationDTO huaWeiOrganizationDTO) {
        //判断是否超出上级菜单角色
        Organization organization = new Organization();
//        organization.setOrgType(OrganizationOrgTypeEnum.get(ContextUtil.getSystemScene()));
        organization.setOrgType(OrganizationOrgTypeEnum.OTHER);
        organization.setName(huaWeiOrganizationDTO.getName());
        organization.setHuaweiOrgId(huaWeiOrganizationDTO.getHuaweiOrgId());
        if (StringUtils.isNotBlank(huaWeiOrganizationDTO.getHuaweiOrgId())) {
            //判断是否存在
            Organization queryorganization = new Organization();
            queryorganization.setHuaweiOrgId(huaWeiOrganizationDTO.getHuaweiOrgId());
            List<Organization> organizationList = listOfOrganization(queryorganization, null);
            if (CollectionUtil.isNotEmpty(organizationList)) {
                huaWeiOrganizationDTO.setOrgId(organizationList.get(0).getId() + "");
                return huaWeiOrganizationDTO;
            }
        }
        if (StringUtils.isNotBlank(huaWeiOrganizationDTO.getParentId())) {
            Organization queryorganization = new Organization();
            queryorganization.setHuaweiOrgId(huaWeiOrganizationDTO.getParentId());
            List<Organization> organizationList = listOfOrganization(queryorganization, null);
            if (CollectionUtil.isNotEmpty(organizationList)) {
                organization.setParentId(organizationList.get(0).getId());
            }
        }
        if (organization.getParentId() == null) {
            //找系统顶级组织
            Organization queryOrganization = new Organization();
            queryOrganization.setParentId(BusinessConstant.parentId);
            queryOrganization.setOrgType(OrganizationOrgTypeEnum.get(ContextUtil.getSystemScene()));
            List<Organization> parentOrgList = listOfOrganization(queryOrganization, null);
            log.info(" 找系统顶级组织 parentOrgList is {}", JSONObject.toJSONString(parentOrgList));
            if (CollectionUtil.isNotEmpty(parentOrgList)) {
                organization.setParentId(parentOrgList.get(0).getId());
            }
        }
        log.info(" 创建org data is {}", JSONObject.toJSONString(organization));
        save(organization);
        huaWeiOrganizationDTO.setOrgId(organization.getId() + "");
        return huaWeiOrganizationDTO;
    }

    @Override
    public HuaWeiOrganizationDTO sycnOrgOfUpd(HuaWeiOrganizationDTO huaWeiOrganizationDTO) {
        Organization queryorganization = new Organization();
        if (StringUtils.isNotBlank(huaWeiOrganizationDTO.getHuaweiOrgId())) {
            queryorganization.setHuaweiOrgId(huaWeiOrganizationDTO.getHuaweiOrgId());
        }
        if (StringUtils.isNotBlank(huaWeiOrganizationDTO.getOrgId())) {
            queryorganization.setId(Long.parseLong(huaWeiOrganizationDTO.getOrgId()));
        }
        List<Organization> organizationList = listOfOrganization(queryorganization, null);
        if (CollectionUtil.isNotEmpty(organizationList)) {
            Organization organization = organizationList.get(0);
            organization.setName(huaWeiOrganizationDTO.getName());
            if (huaWeiOrganizationDTO.getStatus() != null && huaWeiOrganizationDTO.getStatus() == 1) {
                organization.setIsEnabled(BusinessConstant.NO);
            } else if (huaWeiOrganizationDTO.getStatus() != null && huaWeiOrganizationDTO.getStatus() == 0) {
                organization.setIsEnabled(BusinessConstant.YES);
            }
            if (StringUtils.isNotBlank(huaWeiOrganizationDTO.getParentId())) {
                queryorganization = new Organization();
                queryorganization.setHuaweiOrgId(huaWeiOrganizationDTO.getParentId());
                organizationList = listOfOrganization(queryorganization, null);
                if (CollectionUtil.isNotEmpty(organizationList)) {
                    organization.setParentId(organizationList.get(0).getId());
                }
            }
            updateById(organization);
        }
        return huaWeiOrganizationDTO;
    }

    @Override
    public HuaWeiOrganizationDTO sycnOrgOfDel(HuaWeiOrganizationDTO huaWeiOrganizationDTO) {
        Organization queryorganization = new Organization();
        if (StringUtils.isNotBlank(huaWeiOrganizationDTO.getHuaweiOrgId())) {
            queryorganization.setHuaweiOrgId(huaWeiOrganizationDTO.getHuaweiOrgId());
        }
        if (StringUtils.isNotBlank(huaWeiOrganizationDTO.getOrgId())) {
            queryorganization.setId(Long.parseLong(huaWeiOrganizationDTO.getOrgId()));
        }
        List<Organization> organizationList = listOfOrganization(queryorganization, null);
        if (CollectionUtil.isNotEmpty(organizationList)) {
            Organization organization = organizationList.get(0);
            organization.setIsDeleted(BusinessConstant.YES);
            updateById(organization);
        }
        return huaWeiOrganizationDTO;
    }


    public List<OrganizationVo> assemblyTree(List<OrganizationVo> organizationVoList) {
        for (OrganizationVo organizationVo : organizationVoList) {
            if (organizationVo.getChildVoList() != null && !organizationVo.getChildVoList().isEmpty()) {
                assemblyTree(organizationVo.getChildVoList());
            }
            if (organizationVo.getOrgType() != null) {
                organizationVo.setDataType("org");
            }
            List<OrganizationVo> childVoList2 = organizationVo.getChildVoList();
            List<UserAccountVo> userAccountVoList = organizationVo.getUserAccountVoList();
            if (childVoList2 == null || childVoList2.isEmpty()) {
                childVoList2 = new ArrayList<>();
            }
            for (OrganizationVo organizationVo1 : childVoList2) {
                organizationVo1.setDataType("org");
            }
            if (userAccountVoList != null && !userAccountVoList.isEmpty()) {
                for (UserAccountVo userAccountVo : userAccountVoList) {
                    OrganizationVo organizationVo1 = new OrganizationVo();
                    organizationVo1.setName(organizationVo.getName() + "|" + userAccountVo.getRealName());
                    organizationVo1.setId(userAccountVo.getId());
                    organizationVo1.setDataType("user");
                    organizationVo1.setParentId(organizationVo.getParentId());
                    childVoList2.add(organizationVo1);
                }
            }
            organizationVo.setChildVoList(childVoList2);
        }

        return organizationVoList;
    }

    public List<DataTreeVo> assemblyToDataTree(List<DataTreeVo> dataTreeVos, List<OrganizationVo> organizationVoList) {
        for (OrganizationVo organizationVo : organizationVoList) {
            DataTreeVo dataTreeVo = new DataTreeVo();
            BeanUtils.copyProperties(organizationVo, dataTreeVo);
            if ("user".equals(organizationVo.getDataType())) {
                dataTreeVo.setOrgName(organizationVo.getName().substring(0, organizationVo.getName().indexOf("|")));
                dataTreeVo.setName(organizationVo.getName().substring(organizationVo.getName().indexOf("|") + 1));

            }
            if (organizationVo.getChildVoList() != null && !organizationVo.getChildVoList().isEmpty()) {
                List<DataTreeVo> childVoList = dataTreeVo.getTreeChildVoList();
                if (childVoList == null || childVoList.isEmpty()) {
                    childVoList = new ArrayList<>();
                }
                dataTreeVo.setTreeChildVoList(assemblyToDataTree(childVoList, organizationVo.getChildVoList()));
            }
            dataTreeVos.add(dataTreeVo);
        }
        return dataTreeVos;
    }
}
